#include <iostream>
#include <algorithm>
#include <string>
#include <cstdio>
#include <vector>
#include <stack>
#include <queue>
#include <set>
using namespace std;
class Solution
{
public:
    int dir[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
    int islandPerimeter(vector<vector<int>> &grid)
    {
        int csum = 0, h = grid.size();
        for (int i = 0; i < h; ++i)
        {
            for (int j = 0; j < grid[i].size(); ++j)
            {
                if (grid[i][j] == 0)
                    continue;
                for (int m = 0; m < 4; ++m)
                {
                    int dx = dir[m][0], dy = dir[m][1];
                    if (i + dx < 0 || i + dx >= h || j + dy < 0 || j + dy >= grid[i].size() || grid[i + dx][j + dy] == 0)
                        csum++;
                }
            }
        }
        return csum;
    }
};